﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AI.Steering
{
    /// <summary>
    /// 躲避障碍物
    /// </summary>
    public class SteeringForEvadeObstacle : Steering
    {
        public int[] angles = { -30, 0, 30 };
        [Tooltip("发送射线的位置")]
        public Transform sendPos;
        public override Vector3 GetForce()
        {
            for (int i = 0; i < angles.Length; i++)
            {
                //射线检测（期望力）
                Vector3 expectForce = DetectObstacle(i);
                if (expectForce != Vector3.zero)
                {
                    //返回实际力
                    return (expectForce - controller.currentForce) * weight;//权重越大，实际力到达最大越快
                }
            }
            return Vector3.zero;
        }
        [Tooltip("射线长度")]
        public float rayLenth = 5;
        [Tooltip("射线需要检测的障碍物")]
        public LayerMask rayLayer;
        //射线检测障碍物
        private Vector3 DetectObstacle(int index)
        {
            Vector3 dir = Quaternion.AngleAxis(angles[index], sendPos.up) * sendPos.forward;
            //Quaternion.Euler(0, angles[index], 0) 沿y轴旋转度数，乘以世界坐标按世界，乘以自身坐标按自身
            //Quaternion.AngleAxis(angles[index],sendPos.up)按自身的y轴旋转度数
            RaycastHit hit;
            if (Physics.Raycast(sendPos.position, dir, out hit, rayLenth, rayLayer))
            {
                //期望力
                return (hit.point - hit.transform.position).normalized * speed;
            }
            else
            {
                return Vector3.zero;
            }
            
        }
        private void Update()
        {
            for (int i = 0; i < angles.Length; i++)
            {
                Debug.DrawLine(sendPos.position,sendPos.position + Quaternion.AngleAxis(angles[i],sendPos.up)*transform.forward*rayLenth);
            }
        }
    }
}

